// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

//引用TcbRouter
const TcbRouter = require('tcb-router')

/**
 * 成功的数据结构
 */
const getSuccessData = (data = {}) => ({
  status: 200,
  data: {
    status: 0,
    data
  }
})

/**
 * 失败的数据结构
 */
const getFailData = (data = {}) => ({
  status: 401,
  data: {
    ...data
  }
})

/**
 * 根据id获取时间戳
 *
 * @param {*} id
 * @returns
 */
function getTimeWithId(id) {
  // 这里为什么要乘以 1000 ？乘以1000之后表示“毫秒”。
  const time = parseInt(id.toString().substring(0, 8), 16) * 1000;
  // 这个是“秒”
  // const time = parseInt(id.toString().substring(0, 8), 16);

  return time;
}

/**
 * 走进永昌 数据的过滤器
 *
 * @param {*} res
 */
function goDataFilter(res) {
  const {
    data: result
  } = res
  // 这是“走进永昌/轮播图”，这个二级分类的id
  const categoryId1 = "5de328e2e887230e08f4fdf8";
  const swiper_imgs = result
    .filter(item => item.categoryId === categoryId1)
    .map(item => item.imgs)[0]

  // 这是“走进永昌/永昌服务”，这个二级分类的id
  const categoryId2 = "5de32f766896be05f40883b3";
  const listServe = result
    .filter(item => item.categoryId === categoryId2)
    .map(item => {
      const {
        _id,
        imgs,
        title,
        article
      } = item;
      const time = getTimeWithId(_id);
      return {
        img_list: imgs,
        text: {
          title,
          article
        },
        time
      }
    })

  // 这是“走进永昌/案例展示”，这个二级分类的id
  const categoryId3 = "5de32f806896be05f40883b4";
  const listShow = result
    .filter(item => item.categoryId === categoryId3)
    .map(item => {
      const {
        _id,
        imgs,
        title,
        article
      } = item;
      const time = getTimeWithId(_id);
      return {
        img_list: imgs,
        text: {
          title,
          article
        },
        time
      }
    })

  // 这是“走进永昌/咨询中心”，这个二级分类的id
  const categoryId5 = "5de32f956896be05f40883b6";
  const listAsk = result
    .filter(item => item.categoryId === categoryId5)
    .map(item => {
      const {
        _id,
        imgs,
        title,
        article,
        articleText
      } = item;
      const time = getTimeWithId(_id);
      return {
        img_list: imgs,
        text: {
          title,
          article,
          articleText
        },
        time
      }
    })

  // 这是“走进永昌/关于永昌”，这个二级分类的id
  const categoryId4 = "5de32f8e6896be05f40883b5";
  const listAbout = result
    .filter(item => item.categoryId === categoryId4)
    .map(item => {
      const {
        _id,
        imgs,
        title,
        article,
        articleText
      } = item;
      const time = getTimeWithId(_id);
      return {
        img_list: imgs,
        text: {
          title,
          article,
          articleText
        },
        time
      }
    })

  return {
    swiper_imgs,
    listServe,
    listShow,
    listAbout,
    listAsk
  }
}

// 云函数入口函数
exports.main = async (event, context) => {

  const app = new TcbRouter({
    event
  })

  /**
   * 初始化admin中的go页面
   */
  app.router('/index', async (ctx, next) => {
    // 这是“走进永昌”，这个一级分类的id
    const pCategoryId = "5de31d24b0f80726901430c9";
    // 过滤 轮播图
    const filterId = '5de328e2e887230e08f4fdf8'

    const resultProduct = await cloud.database().collection("products").where({
      pCategoryId
    }).get()
    const dataProduct = goDataFilter(resultProduct)
    const resultCategory = await cloud.database().collection("categorys").where({
      parentId: pCategoryId
    }).get()
    const {
      data: dataResultCategory
    } = resultCategory
    // 这里要 转化为string类型
    const dataCategory = dataResultCategory.filter(item => item._id + '' !== filterId).map(item => ({
      text: item.name
    }))
    const temp = {
      ...dataCategory[2]
    };
    dataCategory[2] = {
      ...dataCategory[3]
    };
    dataCategory[3] = temp

    dataCategory[0].url = 'cloud://cake-shop-001-gppbo.6361-cake-shop-001-gppbo-1258172236/go_nav/nav_service.png';
    dataCategory[1].url = 'cloud://cake-shop-001-gppbo.6361-cake-shop-001-gppbo-1258172236/go_nav/nav_show.png';
    dataCategory[2].url = 'cloud://cake-shop-001-gppbo.6361-cake-shop-001-gppbo-1258172236/go_nav/nav_center.png';
    dataCategory[3].url = 'cloud://cake-shop-001-gppbo.6361-cake-shop-001-gppbo-1258172236/go_nav/nav_about.png';
    dataCategory[4].url = 'cloud://cake-shop-001-gppbo.6361-cake-shop-001-gppbo-1258172236/go_nav/nav_call.png';

    ctx.body = getSuccessData({
      ...dataProduct,
      listNav: dataCategory
    })
  })

  /**
   * 获取、添加或者更新。
   * “走进永昌”、“精选案例”、“装修咨询”和“会员中心”。
   * 这些二级详情界面的 detail_two 的标题的图片。
   */
  app.router('/imagesOfTitles', async (ctx, next) => {
    try {
      const {
        data
      } = await db.collection("images_titles").get()

      ctx.body = getSuccessData(data)

    } catch (error) {
      ctx.body = getFailData({
        status: 1,
        msg: '获取二级详情界面的标题图片失败',
        error
      })
    }
  })

  /**
   * 修改二级界面中的标题图片
   */
  app.router('/updateImagesOfTitles', async (ctx, next) => {
    const {
      images_serve,
      images_show,
      images_about,
      images_ask,
      images_contact_us,
    } = event.other

    let updateData = {}
    if (undefined !== images_serve && null !== images_serve) updateData.images_serve = images_serve
    if (undefined !== images_show && null !== images_show) updateData.images_show = images_show
    if (undefined !== images_about && null !== images_about) updateData.images_about = images_about
    if (undefined !== images_ask && null !== images_ask) updateData.images_ask = images_ask
    if (undefined !== images_contact_us && null !== images_contact_us) updateData.images_contact_us = images_contact_us
    if (updateData === {}) ctx.body = getSuccessData()

    try {
      await db.collection("images_titles")
        .where({
          _id: '5def18e497bd6e21189c53f5'
        })
        .update({
          data: updateData
        })

      ctx.body = getSuccessData()

    } catch (error) {

      ctx.body = getFailData({
        status: 1,
        msg: '获取二级详情界面的标题图片失败',
        error
      })

    }
  })

  /**
   * 获取留言板的信息。
   * 一次返回十个
   */
  app.router('/getMessageBoard', async (ctx, next) => {
    let {
      page,
      size,
      name,
      phone,
      message,
      status
    } = event.other

    let condition = {}
    if (undefined !== name) {
      condition = {
        name: new RegExp(`^.*${name}.*$`)
      }
    } else if (undefined !== phone) {
      condition = {
        phone: new RegExp(`^.*${phone}.*$`)
      }
    } else if (undefined !== message) {
      condition = {
        textarea: new RegExp(`^.*${message}.*$`)
      }
    } else if (undefined !== status) {
      condition = {
        status
      }
    }

    try {
      page = page * 1
      size = size * 1

      const {
        total
      } = await db.collection("messages_boards").where(condition).count()
      const {
        data: list
      } = await db.collection("messages_boards")
        .where(condition)
        .skip((page - 1) * size)
        .limit(size)
        .orderBy('_id', 'desc')
        .get()
      const data = {
        pageNum: page,
        total,
        pages: Math.floor((total + size - 1) / size),
        pageSize: size,
        list,
      }

      ctx.body = getSuccessData(data)

    } catch (error) {

      ctx.body = getFailData({
        status: 1,
        msg: '留言板获取信息失败。',
        error
      })

    }
  })

  /**
   * 更新留言板的状态
   */
  app.router('/updateMessageBoardStatus', async (ctx, next) => {
    const {
      _id,
      status
    } = event.other

    try {

      const {
        data
      } = await db.collection("messages_boards").doc(_id).update({
        data: {
          status
        }
      })

      ctx.body = getSuccessData(data)

    } catch (error) {

      ctx.body = getFailData({
        status: 1,
        msg: '留言板更新状态失败。',
        error,
      })

    }
  })

  return app.serve()
}